import React, { useState } from 'react';
import {
  InputNumber,
  Popconfirm,
  Button,
  Card,
  Modal,
  Form,
  Image,
  Descriptions,
  Tabs,
  Radio,
  Badge,
} from 'antd';
import columnsData, { columnsDataType } from './data';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import {
  getThemeByThemeNo,
  getFragmentsByThemeNo,
  putOnShelves,
  pullOffShelves,
} from './service';
import styles from './index.css';
import { lowerFirst } from '@antv/util';
import { getLocalStorageInfo } from '@/utils/localStorageInfo';

export default ({ isFragments, viewSerialNo, setIsLoadCastingDetail }) => {
  // 控制上架模态框
  const [isCheckDetailModal, setIsCheckDetailModal] = useState(false);
  // 控制下架模态框
  const [pullModal, setPullModal] = useState(false);
  // 主题详情
  const [themeInfo, setThemeInfo] = useState({});
  // 上架商品详情
  const [merchandiseInfo, setMerchandiseInfo] = useState({});
  // 表头
  const columns: ProColumns<columnsDataType>[] = columnsData;
  // 操作行数据 自定义操作行
  const actionRender: any = (text: any, record: any, index: number) => (
    <ul className="ant-list-item-action" style={{ margin: 0 }}>
      {record.totalSupply !== record.inventory ? (
        <li>
          <a
            onClick={() => {
              pullFormRef.setFieldsValue({
                quantity: Number(record.totalSupply - record.inventory),
              });
              setMerchandiseInfo(record);
              setPullModal(true);
            }}
          >
            下架
          </a>
          <em className="ant-list-item-action-split"></em>
        </li>
      ) : null}
      {record.inventory > 0 ? (
        <li>
          <a
            onClick={() => {
              formRef.setFieldsValue({
                quantity: Number(record.inventory),
              });
              setMerchandiseInfo(record);
              setIsCheckDetailModal(true);
            }}
          >
            上架
          </a>
        </li>
      ) : null}
    </ul>
  );
  // 自定义数据的表格头部数据
  columns.forEach((item: any) => {
    item.dataIndex === 'action' ? (item.render = actionRender) : undefined;
  });

  React.useEffect(() => {
    getThemeInfo();
  }, [viewSerialNo]);

  // 获取主题详情
  const getThemeInfo = async () => {
    let res = await getThemeByThemeNo({ serialNo: viewSerialNo });
    console.log(res);
    setThemeInfo(res.data);
  };

  // 上架模态框确定
  const handleOk = () => {
    formRef.validateFields().then(async () => {
      var response = formRef.getFieldsValue();
      console.log(response);
      let customerNo = getLocalStorageInfo('customerInfo').customerNo;
      let params = {
        typeNo: themeInfo.serialNo,
        customerNo,
      };
      console.log(merchandiseInfo);
      if (merchandiseInfo.fragmentsSerialNo) {
        params.fragmentsSerialNo = merchandiseInfo.fragmentsSerialNo;
      }
      console.log(params);

      let res = await putOnShelves({
        ...response,
        ...params,
      });
      console.log(res);
      getThemeInfo();
      // 重置表单
      formRef.resetFields();
      // 表格重新渲染
      actionRef.current?.reload();
      setIsCheckDetailModal(false);
    });
  };

  // 下架模态框确定
  const handlePullOk = () => {
    pullFormRef.validateFields().then(async () => {
      var response = pullFormRef.getFieldsValue();
      console.log(response);
      const params = {
        serialNo: merchandiseInfo.goodsNo,
      };
      console.log(params);

      let res = await pullOffShelves({
        ...response,
        ...params,
      });
      console.log(res);
      getThemeInfo();
      // 重置表单
      pullFormRef.resetFields();
      // 表格重新渲染
      actionRef.current?.reload();
      setPullModal(false);
    });
  };

  // 上架表单验证 获取表单
  const [formRef] = Form.useForm();
  // 下架表单验证 获取表单
  const [pullFormRef] = Form.useForm();
  const actionRef = React.useRef<ActionType>();
  return (
    <>
      <Card
        title="主题信息"
        extra={
          <>
            {themeInfo?.fragmentsFlag == 0 ? (
              <>
                {themeInfo?.totalSupply > themeInfo?.inventory ? (
                  <Button
                    type="primary"
                    onClick={() => {
                      pullFormRef.setFieldsValue({
                        quantity: Number(
                          themeInfo?.totalSupply - themeInfo?.inventory,
                        ),
                      });
                      setMerchandiseInfo(themeInfo);
                      setPullModal(true);
                    }}
                    style={{
                      marginRight: '10px',
                    }}
                  >
                    下架
                  </Button>
                ) : null}
                {themeInfo?.inventory > 0 ? (
                  <Button
                    type="primary"
                    onClick={() => {
                      formRef.setFieldsValue({
                        quantity: Number(themeInfo.inventory),
                      });
                      setMerchandiseInfo(themeInfo);
                      setIsCheckDetailModal(true);
                    }}
                    style={{
                      marginRight: '10px',
                    }}
                  >
                    上架
                  </Button>
                ) : null}
              </>
            ) : null}
            <Button
              type="primary"
              onClick={() => {
                setIsLoadCastingDetail(false);
              }}
            >
              返回
            </Button>
          </>
        }
        style={{ marginBottom: 16 }}
      >
        <Descriptions>
          <Descriptions.Item label="主题名称">
            {themeInfo?.themeName}
          </Descriptions.Item>
          <Descriptions.Item label="主题性别">
            {themeInfo?.sex == 0
              ? '男'
              : themeInfo?.sex == 1
              ? '女'
              : themeInfo?.sex == 2
              ? '无性别'
              : '数据库出错'}
          </Descriptions.Item>
          <Descriptions.Item label="有无碎片">
            {themeInfo?.fragmentsFlag == 0
              ? '无'
              : themeInfo?.fragmentsFlag == 1
              ? '有'
              : null}
          </Descriptions.Item>
          <Descriptions.Item label="主题总量">
            {themeInfo?.totalSupply}
          </Descriptions.Item>
          <Descriptions.Item label="库存量">
            {themeInfo?.inventory || 0}
          </Descriptions.Item>
          <Descriptions.Item label="流通状态">
            {themeInfo?.status == 0
              ? '流通中'
              : themeInfo?.status == 1
              ? '未流通'
              : '数据库出错'}
          </Descriptions.Item>
          <Descriptions.Item label="合约名称">
            {themeInfo?.contract?.contractName}
          </Descriptions.Item>
          <Descriptions.Item label="合约编号" span={2}>
            {themeInfo?.contract?.serialNo}
          </Descriptions.Item>
          <Descriptions.Item label="合约模板编号" span={3}>
            {themeInfo?.contract?.contractTemplateNo}
          </Descriptions.Item>
          <Descriptions.Item label="合约地址" span={3}>
            {themeInfo?.contract?.contract}
          </Descriptions.Item>
          <Descriptions.Item label="nft预览">
            <Image width={200} src={themeInfo?.metadataImage} />
          </Descriptions.Item>
        </Descriptions>
      </Card>
      {themeInfo?.fragmentsFlag == 1 ? (
        <Card style={{ marginBottom: 16 }}>
          <ProTable
            columns={columns}
            rowKey="serialNo"
            actionRef={actionRef}
            // pagination={{
            //   showQuickJumper: true,
            // }}
            toolBarRender={false}
            search={false}
            request={async (params) => {
              let res = await getFragmentsByThemeNo({
                ...params,
                serialNo: viewSerialNo,
              });
              console.log(res);
              const result = {
                data: res.data,
                total: res.pagination.totalSize,
              };
              return result;
            }}
          />
        </Card>
      ) : null}
      {/* 上架模态框 */}
      <Modal
        title="上架配置"
        visible={isCheckDetailModal}
        onOk={handleOk}
        okText="确定"
        onCancel={() => {
          // 重置表单
          formRef.resetFields();
          setIsCheckDetailModal(false);
        }}
        cancelText="取消"
        centered
      >
        <Form
          name="basic"
          form={formRef}
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          autoComplete="off"
        >
          <Form.Item
            label="上架数量"
            name="quantity"
            rules={[
              {
                required: true,
                message: '不可为空',
              },
            ]}
          >
            <InputNumber
              min={1}
              max={merchandiseInfo?.totalSupply - merchandiseInfo?.quantity}
            />
          </Form.Item>
          {/* {
            merchandiseInfo.type == '4' ?
              <Form.Item
                label="价格"
                name="price"
                rules={[
                  {
                    required: true,
                    message: '不可为空',
                  },
                ]}
              >
                <InputNumber min={1} precision={0} />
              </Form.Item> : null
          } */}
          {themeInfo.inventory == themeInfo?.totalSupply ? (
            <Form.Item
              label="价格"
              name="price"
              rules={[
                {
                  required: true,
                  message: '不可为空',
                },
              ]}
            >
              <InputNumber min={1} precision={0} />
            </Form.Item>
          ) : null}
        </Form>
      </Modal>
      {/* 下架模态框 */}
      <Modal
        title="下架配置"
        visible={pullModal}
        onOk={handlePullOk}
        okText="确定"
        onCancel={() => {
          // 重置表单
          pullFormRef.resetFields();
          setPullModal(false);
        }}
        cancelText="取消"
        centered
      >
        <Form
          name="basic"
          form={pullFormRef}
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          autoComplete="off"
        >
          <Form.Item
            label="下架数量"
            name="quantity"
            rules={[
              {
                required: true,
                message: '不可为空',
              },
            ]}
          >
            <InputNumber
              min={1}
              precision={0}
              max={merchandiseInfo?.totalSupply - merchandiseInfo?.inventory}
            />
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};
